#include "ahuprotocal.h"
#include "ahudata.h"
#include "ahufsm.h"

extern int	mq_id;
extern ahu_dev_t *ahu_dev_hd;

/* 将事件发送给指定的设备 */
void ahu_event_proc(ahu_msg_t *buf)
{
    ES_PRT_INFO("AHU: Dev[%s], Recv event[%d] \n", buf->device_id, buf->fsmevt);

    ahu_dev_t *pos;
    list_for_each_entry(pos, &ahu_dev_hd->list, list){
        /* 根据device_id 找到这个设备 */
        if(strcmp(pos->device_id, buf->device_id) == 0){
            fsm_do(buf->fsmevt, pos);
        }
    }
}

/* 接收事件，分类处理 */
void *ahu_event_thread(void *arg)
{
    pthread_detach(pthread_self());

    ahu_msg_t rx_msg;

    int cnt;

    while(1){
        memset(&rx_msg, 0, sizeof(rx_msg));
        cnt = msgrcv(mq_id, &rx_msg, sizeof(rx_msg)-sizeof(rx_msg.mtype), AHU_MQTP_EVENT, 0);
        if(cnt < 0){
            ES_PRT_WARN("CPO: msgrcv in protocal thread errno: %s \n", strerror(errno));
        }

        ahu_event_proc(&rx_msg);
    }

    return NULL;
}